//一般直接写在一个js文件中
layui.use(['element', 'form', 'table', 'upload', 'layer', 'laydate'], function () {
    var $ = layui.jquery
        , upload = layui.upload
        , layer = layui.layer
        , form = layui.form
        , laydate = layui.laydate;

    //执行一个laydate实例
    laydate.render({
        elem: '#birthday' //指定元素
    });

    //身份证正面
    upload.render({
        elem: '#identityCardJust'
        , url: '/storage/files/ul'
        , field: 'file'
        , accept: "images"
        , acceptMime: "image/jpg,image/jpeg,image/png"
        , size: 5120
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            var that = this;
            obj.preview(function (index, file, result) {
                $(that.elem).attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.code != 200) {
                return layer.msg('上传失败');
            }
            //上传成功
            var $target = $(this.elem);
            $target.parent().parent().find(".identityCardJust").val(res.data.path);

        }
        , error: function () {
            //演示失败状态
            var $target = $(this.elem);
            var demoText = $target.parent().find(".msg-box")
            demoText.html('<span style="color: #FF5722;">上传失败!</span>');
        }
    });
    //身份证反面
    upload.render({
        elem: '#identityCardAgainst'
        , url: '/storage/files/ul'
        , field: 'file'
        , accept: "images"
        , acceptMime: "image/jpg,image/jpeg,image/png"
        , size: 5120
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            var that = this;
            obj.preview(function (index, file, result) {
                $(that.elem).attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.code != 200) {
                return layer.msg('上传失败');
            }
            //上传成功
            var $target = $(this.elem);
            $target.parent().parent().find(".identityCardAgainst").val(res.data.path);

        }
        , error: function () {
            //演示失败状态
            var $target = $(this.elem);
            var demoText = $target.parent().find(".msg-box")
            demoText.html('<span style="color: #FF5722;">上传失败!</span>');
        }
    });

    //添加证书
    $("#certificateAdd").on("click", function () {
        layer.open({
            type: 2,
            content: '/employee/uploadCertificate',
            area: ['650px', '370px'],
            title: '证书添加',
            btn: ['确定'],
            yes: function (index, layero) {
                var $form = layer.getChildFrame('#form', index);
                var certificateName = $form.find("input[name=certificateName]").val();
                var certificateImg = $form.find("input[name=certificateImg]").val();
                if (certificateName == undefined || certificateName == "" || certificateImg == undefined || certificateImg == "") {
                    return layer.msg("请填写必填项，*号代表必填")
                }
                $("#tbody").append(
                    '<tr>' +
                    '     <td class="certificateName">' + certificateName + '</td>' +
                    '     <td class="certificateImg">' + '<img class="layui-upload-img" data-imgsrc="' + certificateImg + '"  src="/storage/files/' + certificateImg + '"}>' +
                    '     <p class="msg-box">' +
                    '                                <a  target="_blank" href="/storage/files/' + certificateImg + '"  class="layui-btn layui-btn-normal layui-btn-xs">查看</a>' +
                    '                                <a  href="/storage/files/dl/' + certificateImg + '"  class="layui-btn layui-btn-normal  layui-btn-xs">下载</a>' +
                    '      </p>' +
                    '     </td>' +
                    '     <td>' + '<button type="button" class="layui-btn layui-btn-sm delete">删除</button>' + '</td>' +
                    ' </tr>'
                );
                $(".delete").on("click", function () {
                    $(this).parent().parent().remove();
                });
                layer.close(index)
            }
        });
    });

    //添加培训记录
    $("#trainAdd").on("click", function () {
        layer.open({
            type: 2,
            content: '/employee/uploadTrainAdd',
            area: ['650px', '550px'],
            title: '证书添加',
            btn: ['确定'],
            yes: function (index, layero) {
                var $form = layer.getChildFrame('#form', index);
                var trainName = $form.find("input[name=trainName]").val();
                var trainDate = $form.find("input[name=trainDate]").val();
                var trainOrganization = $form.find("input[name=trainOrganization]").val();
                var trainGrade = $form.find("input[name=trainGrade]").val();
                var uploadOneImg = $form.find("input[id=uploadOneImg]").val();
                var uploadTwoImg = $form.find("input[id=uploadTwoImg]").val();
                if (trainName == undefined || trainName == "" || trainDate == undefined || trainDate == "" || trainOrganization == undefined || trainOrganization == "" || trainGrade == undefined || trainGrade == "") {
                    return layer.msg("请填写必填项，*号代表必填")
                }
                var img = "";
                if (uploadOneImg !== undefined && uploadOneImg !== "") {
                    img +=
                        '<div style="float: left">' +
                        '<img class="layui-upload-img"   src="/storage/files/' + uploadOneImg + '">' +
                        '<p class="msg-box">' +
                        '  <a  target="_blank" href="/storage/files/' + uploadOneImg + '"  class="layui-btn layui-btn-normal layui-btn-xs">查看</a>' +
                        ' <a  href="/storage/files/dl/' + uploadOneImg + '"  class="layui-btn layui-btn-normal  layui-btn-xs">下载</a>' +
                        '</p>' +
                        '</div>'
                }
                if (uploadTwoImg !== undefined && uploadTwoImg !== "") {
                    img +=
                        '<div style="float: left">' +
                        '<img class="layui-upload-img"   src="/storage/files/' + uploadTwoImg + '">' +
                        ' <p class="msg-box">' +
                        '       <a  target="_blank" href="/storage/files/' + uploadTwoImg + '"  class="layui-btn layui-btn-normal layui-btn-xs">查看</a>' +
                        '        <a  href="/storage/files/dl/' + uploadTwoImg + '"  class="layui-btn layui-btn-normal  layui-btn-xs">下载</a>' +
                        ' </p>' +
                        '</div>'
                }
                $("#tbody1").append(
                    '<tr>' +
                    '     <td class="trainName" height="115px">' + trainName + '</td>' +
                    '     <td class="trainDate">' + trainDate + '</td>' +
                    '     <td class="trainOrganization">' + trainOrganization + '</td>' +
                    '     <td class="trainGrade">' + trainGrade + '</td>' +
                    '     <td>' + img + '</td>' +
                    '     <td>' + '<button type="button" class="layui-btn layui-btn-sm delete1">删除</button>' + '</td>' +
                    '  <input type="hidden" name="trainImg" class="trainImg" id="uploadOneImg" value="' + uploadOneImg + '">' +
                    '  <input type="hidden" name="trainImg" class="trainImg" id="uploadTwoImg" value="' + uploadTwoImg + '">' +
                    ' </tr>'
                );
                $(".delete1").on("click", function () {
                    $(this).parent().parent().remove();
                });
                layer.close(index)
            }
        });
    });


    // 上传劳动合同
    upload.render({
        elem: '#laborContract1'
        , url: '/storage/files/ul'
        , field: 'file'
        , accept: "images"
        , acceptMime: "image/jpg,image/jpeg,image/png"
        , size: 5120
        , done: function (res) {
            //如果上传失败
            if (res.code == 200) {
                //上传成功
                var $target = $(this.elem);
                $target.parent().parent().find(".laborContract1").val(res.data.path);
                $("#laborContracts").before(
                    '   <div class="layui-upload layui-inline ">\n' +
                    '      <div class="layui-upload-list">\n' +
                    '         <img class="layui-upload-img" data-src="' + res.data.path + '" style="height: 150px;width: 110px" src="/storage/images/' + res.data.path + '_150x110">\n' +
                    '           <p class="msg-box">\n' +
                    '               <button type="button" class="layui-btn layui-btn-danger  layui-btn-xs deleteLaborContract">删除</button>\n' +
                    '            </p>\n' +
                    '       </div>\n' +
                    '   </div>'
                );
                $(".deleteLaborContract").on("click", function () {
                    $(this).parent().parent().remove();
                });
            } else {
                return layer.msg('上传失败');
            }
        }
        , error: function () {
            //演示失败状态
            var $target = $(this.elem);
            var demoText = $target.parent().find(".msg-box")
            demoText.html('<span style="color: #FF5722;">上传失败!</span>');
        }
    });


    //监听选择岗位
    form.on('select(post)', function (data) {
        $("#postName").val($(data.elem).find("[value=" + data.value + "]").text())
    });

    form.on('submit(submitBtn)', function (data) {
        //证书的数据
        var certificates = new Array();
        $("#tbody tr").each(function () {
            var certificateArray = new Array();
            $(this).find("td").each(function (index, element) {
                if (index == 0) {
                    var certificateName = $(this).text();
                    if (certificateName) {
                        certificateArray.push('"name":"' + certificateName + '"');
                    }
                }
                if (index == 1) {
                    var certificateImg = $(this).find("img").data("imgsrc");
                    if (certificateImg) {
                        certificateArray.push('"path":"' + certificateImg + '"');
                    }
                }
            });
            if (certificateArray !== undefined && certificateArray.length != 0) {
                var str = certificateArray.join(",");
                var certificateJson = "{" + str + "}";
                certificates.push(certificateJson);
            }
        });
        data.field.employeeCertificateList = certificates.join("and");

        //培训记录的数据
        //培训名称
        var trains = new Array();
        $("#tbody1 tr").each(function () {
            var trainArray = new Array();
            $(this).find("td").each(function (index, element) {
                if (index == 0) {
                    var trainName = $(this).text();
                    if (trainName) {
                        trainArray.push('"trainName":"' + trainName + '"');
                    }
                }
                if (index == 1) {
                    var trainDate = $(this).text();
                    if (trainDate) {
                        trainArray.push('"trainDate":"' + trainDate + '"');
                    }
                }
                if (index == 2) {
                    var trainOrganization = $(this).text();
                    if (trainOrganization) {
                        trainArray.push('"trainOrganization":"' + trainOrganization + '"');
                    }
                }
                if (index == 3) {
                    var trainGrade = $(this).text();
                    if (trainGrade) {
                        trainArray.push('"trainGrade":"' + trainGrade + '"');
                    }
                }
            });
            var uploadOneImg = $(this).find("#uploadOneImg").val();
            var uploadTwoImg = $(this).find("#uploadTwoImg").val();
            var trainImg = "";
            if (uploadOneImg) {
                trainImg += uploadOneImg;
            }
            if (uploadTwoImg) {
                trainImg += "," + uploadTwoImg
            }
            if (uploadOneImg || uploadTwoImg) {
                trainArray.push('"trainImg":"' + trainImg + '"');
            }
            if (trainArray !== undefined && trainArray.length != 0) {
                var str = trainArray.join(",");
                var trainJson = '{' + str + '}';
                trains.push(trainJson)
            }

        });
        data.field.trainList = trains.join("and");
        var laborContractsArray = new Array();
        $("#uploadLaborContract img[data-src]").each(function () {
            laborContractsArray.push($(this).data("src"));
        });
        data.field.laborContracts = laborContractsArray.join(",");
        $.ajax({
            url: '/employee/save',
            data: {"data": JSON.stringify(data.field)},
            type: 'post',
            dataType: 'json',
            async: false,
            success: function (rs) {
                if (rs.code === 200) {
                    location.href = "/employee"
                } else {
                    layer.msg(rs.message);
                }
            }
        });
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });

    $("#avatarimg").on('click', function () {
        layer.open({
            title: '头像上传编辑器',
            type: 2
            , content: '/static/plugins/fullAvatarEditor/avatarupload.html'
            , area: ['700px', '500px']
        });
    });

    $("#idNo").blur(function () {
        var idNo = $(this).val();
        var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if (reg.test(idNo) === false) {
            layer.msg("请填写正确的身份证号");
            $("#birthday").val("")
        } else {
            if (idNo.length == 15) {
                var s = idNo.substring(0, 6);
                var s1 = idNo.substring(6, 15);
                idNo = s + "19" + s1;
            }
            $("#birthday").val(idNo.substring(6, 10) + "-" + idNo.substring(10, 12) + "-" + idNo.substring(12, 14))
        }

    })
});